package com.joysuch.wwyt.dataimport.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.joysuch.wwyt.dataimport.service.ExcelExportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/data/export")
@Api(tags = "/bp/excelDataExport Excel数据导出")
public class ExcelExportController {

    @Autowired
    private ExcelExportService excelExportService;
    @Value("${wwyt.file.upload.dir}")
    private String templateOutput;

    @GetMapping("/exportData")
    @ApiOperation(value = "excel数据导出")
    @RequiresPermissions("data:export:exportData")
    public void exportData(HttpServletRequest request, HttpServletResponse response, Integer flag) throws IOException {
        String templateName = getTemplateName(flag);
        // 加载模板
        TemplateExportParams params = new TemplateExportParams("template" + File.separator + templateName + ".xlsx");
//       TemplateExportParams params = new TemplateExportParams("F:" + File.separator + "test" + File.separator + templateName + ".xls");
        Map<String, Object> map = excelExportService.getDataMap(request, flag);
        String agent = request.getHeader("User-Agent");
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        // 重置响应对象
        response.reset();
        // 当前日期，用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = templateName + "-" + sdf.format(new Date()) + ".xlsx";
        // 指定下载的文件名--设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + dateStr);
        //response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setHeader("Pragma", "no-cache");
        if (agent.contains("MSIE")) {
            // IE浏览器
            dateStr = URLEncoder.encode(dateStr, "utf-8");
            dateStr = dateStr.replace("+", " ");
        } else {
            // 其它浏览器
            dateStr = URLEncoder.encode(dateStr, "utf-8");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + dateStr);
        //response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    //获取模板名称
    private String getTemplateName(Integer flag) {
        if (flag == 0) {
            return "安全风险分级管控清单";
        } else if (flag == 1) {
            return "危害因素辨识排查清单";
        } else if (flag == 2) {
            return "视频设备清单";
        } else if (flag == 3) {
            return "持证管理";
        } else if (flag == 4) {
            return "清单工作列表";
        } else {
            return null;
        }
    }
}
